package com.zhudeshuai.zhudemolist.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import com.zhu.zhuCore.utils.AssetsUtil;
import com.zhu.zhuCore.utils.ContextProvider;
import com.zhu.zhuCore.utils.EmptyUtil;
import com.zhu.zhuCore.utils.LogUtil;
import com.zhu.zhuCore.utils.ToastUtil;
import com.zhudeshuai.zhudemolist.R;
import com.zhudeshuai.zhudemolist.base.BaseActivity;
import com.zhudeshuai.zhudemolist.bean.realm_bean.Question;
import com.zhudeshuai.zhudemolist.widget.AnswerQuestionDialog;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmResults;

/**
 * 读取word文件，提取内容
 *
 * @author zhudeshuai
 * @since 2018/10/10
 */
public class WordReadDemo extends BaseActivity {

	private final String QUESTION_REGEX = "^【例题\\d?[·•][单多]选题】.*";
	private final String ANSWER_REGEX = "^【答案】.*";
	private final String SELECT_ITEMS_REGEX = "^[A-D]\\..*";
	private Realm mRealm;

	private Handler mHandler = new Handler(new Handler.Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			Question question = (Question) msg.obj;

			mRealm.beginTransaction();
			mRealm.copyToRealm(question);
			mRealm.commitTransaction();
			LogUtil.d("zhu", "insert success");
			return true;
		}
	});


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_word_read_demo);
		mRealm = Realm.getInstance(new RealmConfiguration.Builder(ContextProvider.getApplicationContext())
				.name("QuestionDB.realm").build());

	}


	/**
	 * 加载word
	 *
	 * @param view
	 */
	public void onLoadDoc(View view) {
		ToastUtil.show("题库加载中...", ToastUtil.Type.NORMAL);
		//清空数据
		final RealmResults<Question> all = mRealm.where(Question.class).findAll();
		mRealm.executeTransaction(new Realm.Transaction() {
			@Override
			public void execute(Realm realm) {
				all.deleteAllFromRealm();
			}
		});
		String[] files = null;
		try {
			files = getResources().getAssets().list("doc");
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (files != null) {
			final String[] finalFiles = files;
			new Thread(new Runnable() {
				@Override
				public void run() {
					readDoc(finalFiles);
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							ToastUtil.show("题库加载成功", ToastUtil.Type.SUCCESS);
						}
					});
				}
			}).start();

		}
	}

	private void readDoc(String[] files) {
		for (String file : files) {
			try {
				final List<String> strings = AssetsUtil.readAllLines("doc/" + file);
				Question question = null;
				for (String line : strings) {
					//提取考题
					//1.提取问题       【例题1·多选题】
					if (line.matches(QUESTION_REGEX)) {
						//标题
						LogUtil.d("zhu", "question:" + line);
						question = new Question();
						question.setQuestionDes(line);
					} else if (line.matches(ANSWER_REGEX)) {
						//答案
						String[] split = line.split(" ");
						if (split.length > 0) {
							String s = split[0];
							String[] split1 = s.split("】");
							if (split1.length > 1) {
								question.setAnswerStr(split1[1].trim());
								char[] chars = split1[1].toCharArray();
								if (question != null) {
									for (char aChar : chars) {
										String e = String.valueOf(aChar);
										if (!EmptyUtil.isEmpty(e.trim())) {//防止" "
											question.answerList.add(e);
										}
									}
								}
							}
						}
						{

							if (question != null && !EmptyUtil.isEmpty(question.getQuestionDes()) &&
									!EmptyUtil.isEmpty(question.selectItems) && !EmptyUtil.isEmpty(question.answerList)) {
								//到此为止一个考题对象应该提取完成，开始入库
								question.preSave();
								Message obtain = Message.obtain();
								obtain.obj = question;
								mHandler.sendMessage(obtain);

							}
						}
						question = null;

					} else if (line.matches(SELECT_ITEMS_REGEX)) {
						LogUtil.d("zhu", "选项：" + line);
						if (question != null) {
							String[] split = line.split("\\.");
							if (split.length > 1) {
								question.selectItems.put(split[0], split[1]);
							}
						}
					}


				}

			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}

	/**
	 * 查询
	 *
	 * @param view
	 */
	public void onQuery(View view) {
		RealmResults<Question> all = mRealm.where(Question.class).findAll();
		ToastUtil.show("题库中共有：" + all.size() + "道题");
	}

	/**
	 * 显示答题UI
	 *
	 * @param view
	 */
	public void toShowUI(View view) {

		//去获取数据:随机抽取10道题
		List<Question> data = new ArrayList<>();
		Map<Integer,Question> dataMap = new HashMap<>();
		RealmResults<Question> all = mRealm.where(Question.class).findAll();
		int size = all.size();
		if(size <= 0){
			ToastUtil.show("请先加载题库");
			return;
		}
		for (int i = 0; i < 10; i++) {
			Random random = new Random();
			int pos = random.nextInt(size);
			while (dataMap.containsKey(pos)){
				pos = random.nextInt(size);
			}
			Question value = all.get(pos);
			mRealm.copyFromRealm(value);
			dataMap.put(pos, value);
		}
		data.addAll(dataMap.values());

		AnswerQuestionDialog dialog = new AnswerQuestionDialog(this);
		dialog.setData(data);
		dialog.show();

	}

}
